package org.west.sky.frame.activiti.study.chapter8;

import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.IdentityLink;
import org.activiti.engine.task.IdentityLinkType;
import org.activiti.engine.task.Task;
import org.west.sky.frame.activiti.study.util.ActivitiEngineUtil;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * author: chz
 * date: 2024/9/6
 * description: 任务权限控制
 */
public class RunDemo8_8 extends ActivitiEngineUtil {

    public static void main(String[] args) {
        RunDemo8_8 runDemo8_3 = new RunDemo8_8();
        runDemo8_3.runDemo();
    }

    private void runDemo() {
        loadActivitiConfigAndInitEngine("activiti.cfg.xml");
        ProcessDefinition processDefinition = deployByClassPathResource("processes/chapter8/Chapter8_1.bpmn20.xml");
        System.out.println("流程定义ID:" + processDefinition.getId() + ",流程定义key:" + processDefinition.getKey());
        //根据流程定义id发起流程
        ProcessInstance processInstance = runtimeService.startProcessInstanceById(processDefinition.getId());
        System.out.println("发起流程实例成功，流程实例id:" + processInstance.getId());
        Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
        System.out.println("第一个任务id:" + task.getId() + ",任务名称：" + task.getName());
        taskService.complete(task.getId());
        System.out.println("第一个任务办理完成，没有进行权限控制");
        Task task2 = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();

        //设置任务与人员的关系
        taskService.addCandidateUser(task2.getId(), "zs");
        taskService.addCandidateUser(task2.getId(), "ls");
        taskService.addUserIdentityLink(task2.getId(), "wu", IdentityLinkType.PARTICIPANT);

        //办理任务
        completeTask(task2.getId(), "zl");
        completeTask(task2.getId(), "wu");
        completeTask(task2.getId(), "ls");
        completeTask(task2.getId(), "zs");

        System.out.println("查询流程实例id:" + processInstance.getId() + "的任务办理情况");
        List<HistoricTaskInstance> list = historyService.createHistoricTaskInstanceQuery().processInstanceId(processInstance.getId()).orderByHistoricTaskInstanceStartTime().asc().list();
        for (HistoricTaskInstance taskInstance : list) {
            System.out.println("任务：" + taskInstance.getName() + "的办理人为：" + taskInstance.getAssignee() + ",开始时间："
                    + sdf.format(taskInstance.getStartTime()) + ",结束时间：" + sdf.format(taskInstance.getEndTime()));
        }
        processEngine.close();
    }

    private void completeTask(String taskId, String userId) {
        System.out.println(userId + "尝试办理任务（taskId=" + taskId + "）");
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        if (task == null || task.getAssignee() != null) {
            System.out.println("任务不存在或已被其他候选人办理完成");
            return;
        }


        IdentityLink myLink = null;
        List<IdentityLink> links = taskService.getIdentityLinksForTask(taskId);
        for (IdentityLink link : links) {
            if (link.getUserId().equals(userId)) {
                myLink = link;
                break;
            }
        }

        if (null == myLink) {
            System.out.println(userId + "没有权限查看任务（taskId=" + taskId + "）");
        } else {
            System.out.println(userId + "是任务的" + myLink.getType());
            if (myLink.getType().equals(IdentityLinkType.CANDIDATE)) {
                //认领任务
                taskService.claim(taskId, userId);
                //设置审批变量
                Map<String, Object> variables = new HashMap<>();
                variables.put("task_审批_outcome", "agree");
                taskService.complete(taskId, variables);
                System.out.println(userId + "完成了任务（taskId=" + taskId + "）");
            } else {
                System.out.println(userId + "没有权限办理任务（taskId=" + taskId + "）");
            }
        }
    }


}
